package joc.apt;

import java.io.IOException;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import javax.tools.Diagnostic.Kind;
import javax.tools.JavaFileObject;

@SupportedAnnotationTypes(value = { "*" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class Processor extends AbstractProcessor {

	private Filer filer;
	private Messager messager;
	private Elements elements;

	@Override
	public void init(ProcessingEnvironment env) {
		filer = env.getFiler();
		messager = env.getMessager();
		elements = env.getElementUtils();
	}

	@Override
	public boolean process(Set elements, RoundEnvironment env) {
		String stuff = "";
		for (Element element : env.getRootElements()) {
			if (element instanceof TypeElement) {
				process((TypeElement) element);
			}
		}
		return true;
	}

	private void process(TypeElement element) {
		if (element.getSimpleName().toString().endsWith("JOC")) {
			return;
		}

		String packageName = elements.getPackageOf(element).getQualifiedName().toString();
		String enumName = element.getSimpleName().toString() + "JOC";

		messager.printMessage(Kind.WARNING, "Package: " + packageName, element);

		String enumContent = "package " + packageName + ";\n" + "class " + enumName + " {\n	";
		for (Element member : element.getEnclosedElements()) {
			if (member.getKind() == ElementKind.FIELD) {
				VariableElement field = (VariableElement) member;
				enumContent += "static class " + field.getSimpleName() + " {}\n";
			}
		}
		enumContent += "\n" + "}";

		JavaFileObject file = null;

		try {
			file = filer.createSourceFile(packageName.replace('.', '/') + "/" + enumName, element);
			file.openWriter().append(enumContent).close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}